package edu.whpu.sztz.action.file;

import java.io.File;
import java.io.FileInputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Hibernate;

import com.opensymphony.xwork2.ActionSupport;

import edu.whpu.sztz.model.upload.UploadImage;
import edu.whpu.sztz.services.upload.UploadImageService;

public class FileUploadAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Resource	private UploadImageService uploadImageService;

	private File picdata;
	private String pictitle;
	
	private String state = "SUCCESS";
	private String title = "";
	private String url = "";
	
	private String contentType;
	
	@Override
	public String execute() throws Exception {
		UploadImage image = new UploadImage();
		image.setContent(Hibernate.createBlob(new FileInputStream(picdata), picdata.length()));
		String lastTitle = pictitle.substring(this.pictitle.lastIndexOf(".") + 1, this.pictitle.length());
		this.contentType = getContentType(lastTitle);
		image.setContentType(this.contentType);
		this.uploadImageService.add(image);
		title = title.replace("&", "&amp;").replace("'", "&qpos;").replace("\"", "&quot;").replace("<", "&lt;").replace(">", "&gt;");
		url = getBasePath() + "ajax-json/" + "image-download.action?id=" + image.getId();
		return SUCCESS;
	}
	
	private String getBasePath() {
		HttpServletRequest request = ServletActionContext.getRequest();
		
		String path = ServletActionContext.getServletContext().getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
		return basePath;
	}
	
	private String getContentType(String title) {
		String result = null;
		if ("bmp".equals(title)) {
			result = "image/bmp";
		} else if ("png".equals(title)) {
			result = "image/png";
		} else if ("gif".equals(title)) {
			result = "image/gif";
		} else if ("jpeg".equals(title)) {
			result = "image/jpeg";
		} else if ("jpg".equals(title)) {
			result = "image/jpeg";
		}
		return result;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public File getPicdata() {
		return picdata;
	}

	public void setPicdata(File picdata) {
		this.picdata = picdata;
	}

	public String getPictitle() {
		return pictitle;
	}

	public void setPictitle(String pictitle) {
		this.pictitle = pictitle;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
}
